package cn.accjiyun.controller.library;

import cn.accjiyun.core.controller.BaseController;
import cn.accjiyun.core.entity.PageModel;
import cn.accjiyun.core.utils.WebUtils;
import cn.accjiyun.model.article.QueryArticle;
import cn.accjiyun.model.library.Library;
import cn.accjiyun.service.LibraryService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by jiyun on 2017/2/11.
 */
@Controller
@RequestMapping("/admin/library")
public class AdminLibraryController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminLibraryController.class);

    private static String libraryListPage = getViewPath("/admin/library/library-list");
    private static String addLibraryPage = getViewPath("/admin/library/library-add");

    @Autowired
    private LibraryService libraryService;

    @InitBinder({"library"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("library.");
    }

    @RequestMapping("/createLibrary")
    @ResponseBody
    public String createLibrary(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String libraryTypeString = request.getParameter("libraryType");
            String downloadNumString = request.getParameter("downloadNum");
            //数据验证
            if (!WebUtils.isValidateRealString(libraryTypeString, downloadNumString)
                    || !WebUtils.isNumeric(libraryTypeString, downloadNumString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }

            Library library = new Library();
            library.setTitle(request.getParameter("title"));
            library.setImageUrl(request.getParameter("imageUrl"));
            library.setLibraryUrl(request.getParameter("libraryUrl"));
            library.setLibraryType(Integer.valueOf(libraryTypeString));
            library.setSummary(request.getParameter("summary"));
            library.setPublishTime(WebUtils.stringToTimestamp(request.getParameter("publishTime")));
            library.setDownloadNum(Integer.valueOf(downloadNumString));
            //保存文库
            libraryService.createLibrary(library);
            //返回json数据
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/library/initLibraryList");
        } catch (Exception e) {
            logger.error("AdminLibraryController.createLibrary()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] libraryIds = request.getParameter("libraryId").split(",");
            if (libraryIds != null && libraryIds.length > 0) {
                libraryService.deleteLibraryByIds(libraryIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminLibraryController.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 分页查询文章列表
     */
    @RequestMapping("/getLibraryList")
    @ResponseBody
    public String getLibraryList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryArticle queryArticle = new QueryArticle();
            String libraryTypeString = request.getParameter("libraryType");
            String pageNoString = request.getParameter("pageNo");
            if (!WebUtils.isValidateRealString(pageNoString) || !WebUtils.isNumeric(pageNoString)) {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            if (WebUtils.isValidateRealString(libraryTypeString) && WebUtils.isNumeric(libraryTypeString)) {
                queryArticle.setType(Integer.valueOf(libraryTypeString));
            }
            queryArticle.setQueryKey(request.getParameter("keyword"));
            queryArticle.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryArticle.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            PageModel<Library> page = new PageModel<>();
            page.setPageSize(8);
            page.setPageNo(Integer.valueOf(pageNoString));
            List<Library> libraryList = libraryService.queryLibraryPage(queryArticle, page);
            JsonArray array = new JsonArray();
            for (Library library : libraryList) {
                JsonObject list = new JsonObject();
                list.addProperty("libraryId", library.getLibraryId());
                list.addProperty("libraryType", library.getLibraryType());
                list.addProperty("title", library.getTitle());
                list.addProperty("imageUrl", library.getImageUrl());
                list.addProperty("createTime", WebUtils.timestampToString(library.getCreateTime()));
                list.addProperty("publishTime", WebUtils.timestampToString(library.getPublishTime()));
                list.addProperty("libraryUrl", library.getLibraryUrl());
                list.addProperty("summary", library.getSummary());
                list.addProperty("downloadNum", library.getDownloadNum());
                array.add(list);
            }
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminArticleController.showArticleList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     * 修改文章
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String libraryIdString = request.getParameter("libraryId");
            String libraryTypeString = request.getParameter("libraryType");
            String downloadNumString = request.getParameter("downloadNum");

            //数据验证
            if (!WebUtils.isValidateRealString(libraryIdString, libraryTypeString, downloadNumString)
                    || !WebUtils.isNumeric(libraryIdString, libraryTypeString, downloadNumString)){
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            Library library = libraryService.queryLibraryById(Integer.valueOf(libraryIdString));
            library.setTitle(request.getParameter("title"));
            library.setImageUrl(request.getParameter("imageUrl"));
            library.setLibraryUrl(request.getParameter("libraryUrl"));
            library.setLibraryType(Integer.valueOf(libraryTypeString));
            library.setSummary(request.getParameter("summary"));
            library.setPublishTime(WebUtils.stringToTimestamp(request.getParameter("publishTime")));
            library.setDownloadNum(Integer.valueOf(downloadNumString));

            libraryService.updateLibrary(library);
            // 修改成功返回原列表页面
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminArticleController.updateArticle()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/initAddLibrary")
    public ModelAndView initAddLibrary() {
        ModelAndView model = new ModelAndView();
        model.setViewName(addLibraryPage);
        return model;
    }

    @RequestMapping("/initLibraryList")
    public ModelAndView initLibraryList() {
        ModelAndView model = new ModelAndView();
        model.setViewName(libraryListPage);
        return model;
    }

}
